//给页面添加书籍
//设置页面上原始的数据，以数组形式
var arr = [{
        id: 1,
        picor: './image/shoppingBg_03.jpg',
        name: '这是什么书',
        price: '28.28',
        sum: 0,
        total: 0,
        state: false
    },
    {
        id: 2,
        picor: './image/shoppingBg_06.jpg',
        name: '小狗狗',
        price: '14.21',
        sum: 0,
        total: 0,
        state: false
    }
]
//全选的状态
let stateAll = false
var tab = $('table') //获取表格节点
function original() {
    str = `<tr>
    <th><input type="checkbox" class="checkbox-all" ${stateAll ? 'checked' : '' }>全选</th>
    <th>序号</th>
    <th>商品图片</th>
    <th>商品信息</th>
    <th>单价</th>
    <th>数量</th>
    <th>总价</th>
    <th>操作</th>
    </tr>`
    //遍历数组，获取每个响应的值
    arr.forEach(v => {
        str = str + `    <tr>
        <td> <input type="checkbox" class="checkbox-item" ${v.state ? 'checked' : ''}></td>
        <td>${v.id}</td>
        <td><img src="${v.picor}" alt="shop03"></td>
        <td>${v.name}</td>
        <td>￥${v.price}</td>
        <td><input type="button" name="minus" value="-" ${v.sum==0?'disabled':''}>
        <input type="text" name="amount" value=${v.sum}>
        <input type="button" name="plus" value="+"></td>
        <td width="100px">￥${v.total}</td>
        <td><a href="#" class='collection'>移入收藏</a><br><a href="#"  class='del' >删除</a></td>
        </tr>`
    })
    //显示到table中去
    tab.innerHTML = str
}
//1.添加商品
function add() {
    var butt = $('#addbookbtn')
    var bookname = $('input[name=bookname]')
    var bookprice = $('input[name=bookprice]')
    var bookpicture = $('input[name=bookpicture]')
    //点击表格，设置委托事件
    butt.addEventListener('click', function (e) {
        e = e || window.event
        var tar = e.target || e.srcElement
        //判断获取到的是不是‘添加书籍’的按钮
        if (tar.getAttribute('id') == 'addbookbtn') {
            //获取表单的值，建议一个对象
            var obj = {
                id: random(3, 100),
                picor: bookpicture.value,
                name: bookname.value,
                price: bookprice.value,
                sum: 0,
                total: 0,
                state: false
            }

            //把新的对象加到数组里面
            arr.push(obj)

            //不管全选是否选中，添加商品的时候，都为不选中
            stateAll = false
            //在刷新页面，调用original函数
            original()
           
        }
    })
}

function del() {
    //获取表格的节点
    var teb = $('table')
    //给teb绑定点击事件
    tab.addEventListener('click', function (e) {
        e = e || window.event
        var tar = e.target || e.srcElement
        //2.删除商品
        if (tar.getAttribute('class') == 'del') { //判断点击的是否是删除
            //找到每个数据的id号
            var id = tar.parentElement.parentElement.firstElementChild
                .nextElementSibling.innerHTML
            //finedIndex 返回满足条件的索引
            var index = arr.findIndex(v => v.id == id)
            arr.splice(index, 1)
            //在刷新页面，调用original函数
            original()
        }
        //3.+号功能
        if (tar.getAttribute('name') == 'plus') {
            //找到每个数据的id号
            var id = tar.parentElement.parentElement.firstElementChild
                .nextElementSibling.innerHTML

            arr.find(v => {
                if (v.id == id) {
                    v.sum++
                    v.total = (v.price * v.sum).toFixed(2)

                }


                //在刷新页面，调用original函数
                original()

                // totalprice()
            })
        }
        // 4.-号功能
        if (tar.getAttribute('name') == 'minus') {
            //找到每个数据的id号
            var id = tar.parentElement.parentElement.firstElementChild
                .nextElementSibling.innerHTML
            arr.find(v => {
                if (v.id == id) {
                    v.sum--
                    v.total = (v.price * v.sum)
                }
                //   totalprice()
                //在刷新页面，调用original函数
                original()

            })
        }
        //全选框
        if (tar.getAttribute('class') == 'checkbox-all') {
            stateAll = !stateAll
            console.log(stateAll);
            if (stateAll) {
                arr.forEach((i) => (i.state = true))
            } else {
                arr.forEach((i) => (i.state = false))
            }
            original()
            // var fu = document.querySelectorAll('input[class=checkbox-item]')
            // fu.forEach(v => {
            //     if (tar.checked) {
            //         v.checked = true
            //     } else {
            //         v.checked = false
            //     }
            // })

        }
        //单选
        if (tar.getAttribute('class') == 'checkbox-item') {
            var id = tar.parentElement.parentElement.firstElementChild
                .nextElementSibling.innerHTML
            //判断点击的id是否相等
            let newArr = arr.find(v => v.id == id)
            //如果相等的话,复选的状态取反，每点击一次就变
            newArr.state = !newArr.state
            //在判断数组里面的复选框是否全部为true，在把返回的结果赋给全选框
            stateAll = arr.every(v => v.state == true) //every全部满座条件返回true，只要一个不满足就返回false
            original()


        }
        totalprice()
    })
    //改变输入框的值
    tab.addEventListener('input', function (e) {
        e = e || window.event
        let tar = e.target || e.srcElement
        if (tar.getAttribute('name') == 'amount') {
            let sum = tar.value
            if (sum <= 0 || isNaN(sum)) {
                alert('请输入正确的数字')
                sum = 0
            }
            let id = tar.parentElement.parentElement.firstElementChild
                .nextElementSibling.innerHTML
            let newarr = arr.find(v => v.id == id) //返回满足条件的元素
            newarr.sum = sum
            newarr.total = (newarr.price * sum).toFixed(2)
            //计算总价
            totalprice()
            // //在刷新页面，调用original函数
            original()
        }

    })

}
//总价计算
function totalprice() {
    var totalObj = $('span')
    var sum = 0
    for (let i = 0; i < arr.length; i++) {
        var a = arr[i].total - 0
        sum = sum + a
    }
    totalObj.innerHTML = '￥' + sum.toFixed(2)
}




add()
original()
del()

function $(a) {
    return document.querySelector(a)
}
//随机数
function random(x, y) {
    // 保证m是最小值,n是最大值
    var m = Math.max(x, y) // 80
    var n = Math.min(x, y) // 50
    return Math.floor(Math.random() * (m - n) + n)
}